#! /bin/bash

# Copyright (C) 2017-2020 Huawei Technologies Duesseldorf GmbH
#
# Author: Roberto Sassu <roberto.sassu@huawei.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, version 2 of the
# License.
#
# File: setup_ima_digest_lists_demo
#      Script to automatize setup of digest lists.


function usage() {
    echo "Usage: $0 initial|final [private key (PEM)] [x.509 certificate (PEM)]"
}

if [ -z  "$1" ]; then
    usage
    exit 1
fi

if [ -n "$2" ] && [ -n "$3" ]; then
   sign_opt="-s -v $2 -x $3"
fi

if [ "$1" = "initial" ]; then
    echo "Add digest lists from distribution..."
    setup_ima_digest_lists distro $sign_opt

    initramfs_dir=$(mktemp --directory)

    pushd $initramfs_dir &> /dev/null
    lsinitrd --unpack &> /dev/null
    popd &> /dev/null

    echo "Add unknown files from initial ram disk..."
    setup_ima_digest_lists immutable -i \
        -D $initramfs_dir \
        -E $initramfs_dir/etc/ima/digest_lists \
        $sign_opt

    rm -Rf $initramfs_dir

    if [ -f /etc/ima/ima-policy ]; then
        setup_ima_digest_lists immutable -t metadata -D /etc/ima/ima-policy \
                               $sign_opt
    fi

    if [ -f /etc/infoflow-policy ]; then
        setup_ima_digest_lists immutable -t metadata -D /etc/infoflow-policy \
                               $sign_opt
    fi

    echo "Add unknown files from root filesystem..."
    setup_ima_digest_lists mutable -i -g -t metadata \
        -D / \
        -E /home \
        -E /etc/ima/digest_lists \
        -E /sys \
        -E /run \
        -E /proc \
        -E /dev \
        -E /tmp \
        -E /etc/ima/ima-policy \
        -E /etc/infoflow-policy \
        $sign_opt

    echo "Remove old IMA/EVM/INFOFLOW xattrs..."
    manage_digest_lists -p rm-ima-xattr
    manage_digest_lists -p rm-evm-xattr
    manage_digest_lists -p rm-infoflow-xattr

    echo "Generate IMA measurements list..."
    manage_digest_lists -p gen-ima-list -o binary_runtime_measurements

    if [ -f /usr/bin/attest_ra_client ]; then
        echo "Generate EVM key..."
        attest_ra_client -y -p 0,1,2,3,4,5,6,7,8,9,11,16 -b -r attest.txt
        cp trusted_key.blob /etc/keys
    fi

    echo "Create initial ram disk..."
    dracut -f -e xattr

    echo "Add IMA xattr from digest lists..."
    manage_digest_lists -p add-ima-xattr

    echo "Fix SELinux label of digest lists..."
    restorecon -R -F /etc/ima/digest_lists

    echo "Remount / read-only..."
    mount -oremount,ro /
elif [ "$1" = "final" ]; then
    manage_digest_lists -p add-evm-xattr
fi
